package com.yearner.reviewplan.user.model;

import com.yearner.reviewplan.common.util.MD5Util;
import com.yearner.reviewplan.user.commands.RegisterUserAccountCommand;
import com.yearner.reviewplan.user.data.UserIdGenerator;
import org.springframework.stereotype.Component;

/**
 * @author pengyg
 * @since 2019/10/16
 */
@Component
public class UserFactory {
    private UserIdGenerator idGenerator;
    public UserFactory(UserIdGenerator userIdGenerator){
        this.idGenerator = userIdGenerator;
    }

    private static final String ACCOUNT_MATCH = "^[a-zA-Z]\\w{3,19}";
    private static final int MIN_PASSWORD_LENGTH = 6;

    public static User create(UserId userId, String accountName, String password,Cycle cycle) {
        User user = User.create(userId, accountName, password);
        if (cycle == null) {
            cycle = Cycle.create();
        }
        user.setCycle(cycle);

        return user;
    }

    /**
     * 仅在注册的时候来创建User
     * login 等查询情使用 UserRepresentation
     * @param command
     * @return
     */
    public  User register(RegisterUserAccountCommand command) {
        //验证帐号密码有效
        validAccount(command.getAccountName());
        validPassword(command.getPassword());
        // md5加密
        String md5Pwd = MD5Util.MD5EncodeUtf8Salt(command.getPassword());

        //分配id，创建
        UserId id = idGenerator.generator();

        return create(id,command.getAccountName(),md5Pwd,null);
    }

    private void validAccount(String account) {
        if (account==null || !account.matches(ACCOUNT_MATCH)) {
            throw new RuntimeException("用户名不合法！");
        }
    }

    public void validPassword(String password) {
        if (password==null || password.length()<MIN_PASSWORD_LENGTH) {
            throw new RuntimeException("密码不符合要求，起码6位以上");
        }
    }
}
